import json
from flask import Flask, request, jsonify
from flask_cors import CORS
from loguru import logger
from clients import GerritClient
from executor import WorkflowExecutor

def create_app(gerrit_client:GerritClient, workflow_executor:WorkflowExecutor):
    app = Flask(__name__)
    CORS(app)
    app.config['gerrit_client'] = gerrit_client
    app.config['workflow_executor'] = workflow_executor
    register_routes(app)
    return app

def register_routes(app):
    @app.route('/change_info', methods=['POST'])
    def get_change_info():
        """
        接收前端 POST 请求，根据提供的 Gerrit Change-ID 查询详细信息并返回 JSON。
        路由: POST /change_info
        请求参数: form-data 中 key 为 submitId
        返回格式: JSON
            成功 -> {"success": true,  "message": <gerrit 数据>}
            失败 -> {"success": false, "message": "change_id is null"}, HTTP 400
        """
        change_id = request.form.get('submitId')
        if change_id is None:
            return jsonify({'success': False, 'message': "change_id is null"}), 400
        logger.info(f'Received Gerrit Change-id: {change_id}')
        gerrit_client = app.config['gerrit_client']
        data = gerrit_client.get_change_info_from_gerrit(change_id)
        return jsonify({'success': True, 'message': data}), 200


    @app.route('/account_info', methods=['POST'])
    def get_account_info():
        """
        根据前端提交的 account_id 查询 Gerrit 账户详细信息并返回 JSON。
        路由: POST /account_info
        请求参数: form-data 中 key 为 account_id
        返回格式: JSON
            成功 -> {"success": true,  "message": <账户数据>}
            失败 -> {"success": false, "message": "account_id is null"}, HTTP 400
        """
        account_id = request.form.get('account_id')
        if account_id is None:
            return jsonify({'success': False, 'message': "account_id is null"}), 400
        logger.info(f'Received account_id: {account_id}')
        gerrit_client = app.config['gerrit_client']
        data = gerrit_client.get_account_info_from_gerrit(account_id)
        return jsonify({'success': True, 'message': data}), 200



    @app.route('/analyse', methods=['POST'])
    def analyse():
        """
        接收前端提交的 change_id 与 options,触发代码分析工作流,返回检测结果。
        路由: POST /analyse
        请求参数:
            form-data:
                submitId  : str  - Gerrit change-id
                options   : str  - JSON 字符串，控制检测规则
        返回格式: JSON
            成功 -> {"success": true,  "message": <检测结果>}
            失败 -> {"success": false, "message": <错误信息>}, HTTP 400/404
        """
        change_id = request.form.get('submitId')
        if change_id is None:
            return jsonify({'success': False, 'message': "change_id is null"}), 400
        options = request.form.get('options')
        if options is None:
            return jsonify({'success': False, 'message': "options is null"}), 400
        options = json.loads(options)
        logger.info(f"receive change_id: {change_id}, options: {options}")
        
        workflow_executor = app.config['workflow_executor']
        result = workflow_executor.submit_workflow_run(change_id, options)
        if result['success'] is False:
            if result['message'] == 'workflow time out':
                return jsonify({'success': False, 'message': 'workflow time out'}), 404
            result = {
                'critical_issues': [],
                'high_risk_issues': [],
                "code_quality_issues": []
            }
            return jsonify({'success': True, 'message': result}), 200
        else:
            if result['result'] == None:
                logger.warning(f"变更{change_id}处理结果为{result['message']}")
                result = {
                    'critical_issues': [],
                    'high_risk_issues': [],
                    "code_quality_issues": []
                }
                return jsonify({'success': True, 'message': result}), 200
        return jsonify({'success': True, 'message': result['result']}), 200


    @app.route('/analyse_test', methods=['POST'])
    def analyse_test():
        """
        测试接口：接收 change_id 与 prompt, 触发一次带自定义提示词的代码分析工作流。
        路由: POST /analyse_test
        请求参数:
            form-data:
                submitId: str - Gerrit change-id
                prompt  : str - 自定义 LLM/规则提示词
        返回格式: JSON
            成功 -> {"success": true,  "message": <检测结果>}
            失败 -> {"success": false, "message": <错误信息>}, HTTP 400/404
        """
        change_id = request.form.get('submitId')
        if change_id is None:
            return jsonify({'success': False, 'message': "change_id is null"}), 400
        prompt = request.form.get('prompt')
        if prompt is None:
            return jsonify({'success': False, 'message': "prompt is null"}), 400
        
        options = dict()
        options['prompt'] = prompt

        workflow_executor = app.config['workflow_executor']
        result = workflow_executor.submit_workflow_run(change_id, options)
        if result['success'] is False:
            if result['message'] == 'workflow time out':
                return jsonify({'success': False, 'message': 'workflow time out'}), 404
            result = {
                'critical_issues': [],
                'high_risk_issues': [],
                "code_quality_issues": []
            }
            return jsonify({'success': True, 'message': result}), 200
        else:
            if result['result'] == None:
                logger.warning(f"变更{change_id}处理结果为{result['message']}")
                result = {
                    'critical_issues': [],
                    'high_risk_issues': [],
                    "code_quality_issues": []
                }
                return jsonify({'success': True, 'message': result}), 200
        return jsonify({'success': True, 'message': result['result']}), 200